//package com.pray.security.filter;
//
//import cn.hutool.json.JSONUtil;
//import com.pray.utils.PrayConstants;
//import com.pray.utils.Result;
//import jakarta.annotation.Resource;
//import jakarta.servlet.FilterChain;
//import jakarta.servlet.ServletException;
//import jakarta.servlet.http.HttpFilter;
//import jakarta.servlet.http.HttpServletRequest;
//import jakarta.servlet.http.HttpServletResponse;
//import org.springframework.core.annotation.Order;
//import org.springframework.data.redis.core.StringRedisTemplate;
//
//import java.io.IOException;
//import java.util.Objects;
//import java.util.Optional;
//import java.util.concurrent.TimeUnit;
//
///**
// * <p>
// * FlowLimitFilter
// * <p>
// *
// * @author 春江花朝秋月夜
// * @since 2023/8/29 14:50
// */
////@Component
//@Order(PrayConstants.ORDER_FLOW_LIMIT)
//@Deprecated
//public class FlowLimitFilter extends HttpFilter {
//    @Resource
//    StringRedisTemplate stringRedisTemplate;
//    @Override
//    protected void doFilter(HttpServletRequest request, HttpServletResponse response, FilterChain chain) throws IOException, ServletException {
//        String address = request.getRemoteAddr();
//        if (this.tryCount(address)){
//            chain.doFilter(request,response);
//        }else {
//            this.writeBlockMessage(response);
//            throw new RuntimeException("访问次数过多,您已被限制访问");
//        }
//    }
//    private void writeBlockMessage(HttpServletResponse response) throws IOException {
//        response.setStatus(HttpServletResponse.SC_FORBIDDEN);
//        response.setContentType("applicaion/json:charset=utf-8");
//        response.getWriter().write(JSONUtil.toJsonStr(Result.fail("操作次数过多，请稍后再试试？")));
//    }
//    private boolean tryCount(String ip) {
//        synchronized (ip.intern()){
//            String key = PrayConstants.FLOW_LIMIT_BLOCK + ip;
//            if (Boolean.TRUE.equals(Boolean.TRUE.equals(stringRedisTemplate.hasKey(key)) &&Integer.parseInt(Objects.requireNonNull(stringRedisTemplate.opsForValue().get(key)))>=10)){
//                return false;
//            }
//            return limitPeriodCheck(ip);
//        }
//    }
//
//
//    private boolean limitPeriodCheck(String ip) {
//
//        if (Boolean.TRUE.equals(stringRedisTemplate.hasKey(PrayConstants.FLOW_LIMIT_COUNT + ip))) {
//            Long increment = Optional.ofNullable(stringRedisTemplate.opsForValue().increment(PrayConstants.FLOW_LIMIT_BLOCK + ip,1L)).orElse(0L);
//            if (increment>=10){
//                stringRedisTemplate.opsForValue().set(PrayConstants.FLOW_LIMIT_BLOCK+ip,"1",30,TimeUnit.SECONDS);
//                return false;
//            }else {
//                stringRedisTemplate.opsForValue().set(PrayConstants.FLOW_LIMIT_BLOCK+ip,String.valueOf(increment),30,TimeUnit.SECONDS);
//            }
//        }
//        return true;
//    }
//
//    //限制20次限制请求最大值
//}
